package com.villaday.idf.custom;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.villaday.idf.R;
import com.villaday.idf.base.BaseDialog;
import com.villaday.idf.model.GetMobileCode;
import com.villaday.idf.model.MemberUpgrade;
import com.villaday.idf.model.MemberUpgradeEntity;
import com.villaday.idf.model.RefreshtokenEntity;
import com.villaday.idf.model.Sms;
import com.villaday.idf.model.SmsEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.DesUtil;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PhoneUtil;
import com.villaday.idf.util.ToastUtil;

import java.util.HashMap;
import java.util.Map;

import butterknife.OnTextChanged;


/**
 * 上传凭证 对话框
 */
@SuppressLint("ValidFragment")
public class BindMobileDialog extends BaseDialog implements View.OnClickListener, OkHttpUtil.OnDataListener, TextWatcher {

    private static boolean isUpgradeVip;
    EditText etMobileNum;
    EditText etCode;
    TextView tvGetCode;
    Context context;
    String mobile;
    String Code;
    private BindMobileListener mListener;
    private Handler handler = new Handler();

    private Gson gson = new GsonBuilder().create();
    private final int retryLimit = Constant.Integers.CodeRetryTime;//重试秒数上限
    private int timeNum = retryLimit;//获取验证码倒计时


    public static BindMobileDialog newInstance(Context context,boolean isUpgradeVip ) {
        BindMobileDialog.isUpgradeVip = isUpgradeVip;
        BindMobileDialog dialog = new BindMobileDialog(context);
        Bundle bundle = new Bundle();
        dialog.setArguments(bundle);
        return dialog;
    }

    @SuppressLint("ValidFragment")
    public BindMobileDialog(Context context) {
        this.context = context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Window window = getDialog().getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);//必须放在setContextView之前调用
        View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_bind_mobile, null);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        this.setCancelable(true);
        //宽度撑满
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        //进入退出动画
        window.setWindowAnimations(R.style.animTranslateTop);
        etMobileNum = (EditText) view.findViewById(R.id.et_input_phone);
        etCode = (EditText) view.findViewById(R.id.et_input_code);
        tvGetCode = (TextView) view.findViewById(R.id.tv_get_code);
        TextView btnConfirm = (TextView) view.findViewById(R.id.btn_confirm);
        ImageView ivClose = (ImageView) view.findViewById(R.id.iv_close_dialog);

        btnConfirm.setOnClickListener(this);
        ivClose.setOnClickListener(this);
        tvGetCode.setOnClickListener(this);
        etMobileNum.addTextChangedListener(this);

        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null) {
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            dialog.getWindow().setLayout((int) (dm.widthPixels * 0.85), ViewGroup.LayoutParams.WRAP_CONTENT);
        }
    }


    public void setListener(BindMobileListener icListener) {
        this.mListener = icListener;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_confirm) { //确认绑定手机号
            if (TextUtils.isEmpty(etMobileNum.getText().toString().trim())) {
                ToastUtil.initToast(getActivity(), "请输入手机号");
            } else if (TextUtils.isEmpty(etCode.getText().toString().trim())) {
                ToastUtil.initToast(getActivity(), "请输入短信验证码");
            } else {
                mListener.finishBindMobile(etMobileNum.getText().toString().trim(), etCode.getText().toString().trim(), isUpgradeVip);
            }
        } else if (v.getId() == R.id.iv_close_dialog) {
            mListener.unBindMobile();
            dismiss();
        } else if (v.getId() == R.id.tv_get_code) {//获取短信验证码
            getCode();
        }
    }

    @Override
    public void onResponse(String url, String json) {
        if (!TextUtils.isEmpty(json)) {
            if (Constant.URL.sms.equals(url)) { //刷新Token
                LogeUtil.e("sms", json);
                SmsEntity se = gson.fromJson(json, SmsEntity.class);
                if (Constant.Strings.SUC.equals(se.getCode())) {
                    ToastUtil.initToast(context, "发送成功");
                } else {
                    ToastUtil.initToast(context, "稍后重试");
                }
            }

        }
    }

    @Override
    public void onFailure(String url, String error) {

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s.toString().trim().length() == 11) {
            if (!tvGetCode.isSelected() && timeNum >= retryLimit) {
                tvGetCode.setSelected(true);
            }
        } else {
            if (tvGetCode.isSelected()) {
                tvGetCode.setSelected(false);
            }
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    public interface BindMobileListener {
        void finishBindMobile(String phone, String code,boolean isUpgradeVip);
        void unBindMobile();
    }


    private void getCode() {
        if (tvGetCode.isSelected()) {
            mobile = etMobileNum.getText().toString().trim();
            if (etMobileNum.getText().length() == 0) {
                ToastUtil.initToast(getActivity(), "手机号码不能为空");
            } else if (!mobile.matches(Constant.Strings.RegexMobile)) {
                ToastUtil.initToast(getActivity(), "请输入正确手机号");
            } else {
                tvGetCode.setSelected(false);
                Map<String, Object> map = new HashMap<>();
                OkHttpUtil.postJson(context, Constant.URL.sms, new Sms(402, mobile), map, this);
                //设置XX秒后重试
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (tvGetCode != null) {
                            tvGetCode.setText("点击重新发送 (" + timeNum + ")");
                            if (timeNum > 0) {
                                handler.postDelayed(this, 1000);
                                timeNum--;
                            } else {
                                tvGetCode.setText("发送验证码");
                                timeNum = retryLimit;
                                if (etMobileNum.getText().length() == 11) {
                                    tvGetCode.setSelected(true);
                                }
                            }
                        }
                    }
                });
            }
        } else {
            ToastUtil.initToast(getActivity(), "请稍后重试！");
        }
    }

    private void upTimeNum() {
        if (timeNum < retryLimit) {//倒计时中
            timeNum = 0;
        }
    }

}
